package com.pay.cloud.fragment;

import android.os.Environment;

import com.pay.cloud.DeviceUtils;
import com.pay.cloud.HttpUtil;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import okhttp3.Response;

import static com.pay.cloud.fragment.TipFragment.TipType.WAIT;

public class UpdateFragment extends TipVerticalFragment {
    private OnUpdateListener listener;

    public UpdateFragment() {
        super(WAIT, "正在检查版本");
    }

    @Override
    public boolean useNetwork() {
        return true;
    }

    @Override
    public void execute() throws Exception {
        String curVersion = DeviceUtils.appVersion(getContext());
        String jsonString = HttpUtil.get("http://download.ioopos.com/ioopos-cpay/ioopos-cpay.html");
        JSONObject json = new JSONObject(jsonString);
        String newVersion = json.getString("version");
        String[] curVers = curVersion.split("\\.");
        String[] newVers = newVersion.split("\\.");
        boolean update = false;
        for (int i = 0; i < newVers.length; i++) {
            if (i < curVers.length) {
                if (curVers[i].compareTo(newVers[i]) < 0) {
                    update = true;
                    break;
                }
            } else {
                update = true;
                break;
            }
        }
        if (!update) {
            listener.onChecked(false);
            return;
        }
        listener.onChecked(true);

        String downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        String filePath = downloadDir + File.separator + "ioopos-cpay.apk";

        File file = new File(filePath);
        if (!file.exists()) {
            file.createNewFile();
        }
        file.setWritable(true);
        byte[] bytes = new byte[1024];
        int length;
        Response res = HttpUtil.getResponse(json.getString("apkUrl"));
        final int totalLength = Integer.parseInt(res.header("content-length"));
        int loadedLength = 0;
        try (InputStream is = res.body().byteStream(); FileOutputStream os = new FileOutputStream(file)) {
            while ((length = is.read(bytes)) != -1) {
                os.write(bytes, 0, length);
                loadedLength += length;
                listener.onDownloading(totalLength, loadedLength);
            }
        }
        listener.onDownload(filePath);
    }

    public interface OnUpdateListener {
        void onChecked(boolean toUpdate);
        void onDownloading(int totalLength, int loadedLength);
        void onDownload(String file);
    }

    public void setListener(OnUpdateListener listener) {
        this.listener = listener;
    }

}
